import buffer from '@ohos.buffer';
import util from '@ohos.util';

export const emailPattern: string = "([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9._-]+)"

export class StringUtil {
  static uint8ArrayToString(u8a: Uint8Array): string {
    let u8aBuffer = buffer.from(u8a);
    return u8aBuffer.toString()
  }

  static stringToU8aWithUtf8(str: string): Uint8Array {
    let textEncoder = new util.TextEncoder("utf-8");
    let u8a = textEncoder.encodeInto(str);
    return u8a;
  }

  static regexEmail(str: string): boolean {
    let regex = new RegExp(emailPattern);
    return regex.test(str)
  }

  /**
   * 是否是a-zA-Z的字母
   * @param str
   */
  static isAlphabet(str: string) {
    let regex = new RegExp("[a-zA-Z]+");
    return regex.test(str)
  }

  static regex(rex: string, str: string) {
    return str.match(rex);
  }

  /**
   * u8a 显示其值的字符串序列,radix是进制.
   * @param u8a
   * @returns
   */
  static u8aToStringByValueDisplay(u8a: Uint8Array, radix: number = 10): string {
    if (u8a.length == 0) return "";
    let string = "";
    for (let i = 0; i <= u8a.length - 1; i++) {
      let u8 = u8a[i];
      string += u8.toString(radix);
    }
    return string;
  }

  static uint8ArrayToBase64string(u8a: Uint8Array): string {
    let base64HP = new util.Base64Helper();
    let encodeU8a = base64HP.encodeSync(u8a);
    return StringUtil.uint8ArrayToString(encodeU8a)
  }

  /**
   * 从字符串中获取cid
   * @param source 原始字符串
   * @returns 符合要求的cid字符串
   * @description 通过解析eml获取到的cid，可能会被包含<>或者""中
   */
  static getCid(source: string): string {
    if ((source.startsWith("<") && source.endsWith(">")) || (source.startsWith("\"") && source.endsWith("\""))) {
      return source.substring(1, source.length - 1)
    }
    return source
  }

  /**
   * 字符是否是一个字母
   * A-Z
   * a-z
   * @param c
   * @returns
   */
  static isLetter(charcode: number) {
    return (charcode >= 'A'.charCodeAt(0) && charcode <= 'Z'.charCodeAt(0)) || (charcode >= 'a'.charCodeAt(0) && charcode <= 'z'.charCodeAt(0))

  }

  /**
   * 字符是否是一个数字
   * @param c
   */
  static isDigit(charcode: number) {
    return charcode >= '0'.charCodeAt(0) && charcode <= '9'.charCodeAt(0)
  }

  /**
   * 计算字符串的hash值
   * @param str
   * @returns 字符串hash值
   */
  static hashCode(str: string): number {
    return str.split("").reduce(
      function (a, b) {
        a = ((a << 5) - a) + b.charCodeAt(0);
        return a & a
      }, 0);
  }

  /**
   *
   * @deprecated
   * isNullOrEmpty(str) ? a : str 可以直接改为  str || a
   * @param str
   * @returns
   */
  static isNullOrEmpty(str: string | null) {
    return !(str && str.length > 0);
  }


}
